# -*- coding: utf-8 -*-
# !/usr/bin/env python
from rest_framework.views import APIView
from components.kubernetes.api_file_verify import get_info
from utils.K8S import K8sApi
from utils.views import Result, ReturnClass
from copy import deepcopy


class startCompareDeploymentYaml(APIView):
    def get(self, request):
        data = request.query_params
        old_kubernetes_cluster_id = data['old_kubernetes_cluster_id']
        now_kubernetes_cluster_id = data['now_kubernetes_cluster_id']
        old_version_cluster_select_name = data['old_version_cluster_select_name']
        now_version_cluster_select_name = data['now_version_cluster_select_name']

        old_return_info = get_info(old_kubernetes_cluster_id)
        if ReturnClass.if_ok(old_return_info):
            old_kubernetes_cluster_sign_kubeconfig = ReturnClass.get_value(old_return_info)
        else:
            return Result.fail_response(ReturnClass.get_value(old_return_info))

        now_return_info = get_info(now_kubernetes_cluster_id)
        if ReturnClass.if_ok(now_return_info):
            now_kubernetes_cluster_sign_kubeconfig = ReturnClass.get_value(now_return_info)
        else:
            return Result.fail_response(ReturnClass.get_value(now_return_info))

        now_k8s_api = K8sApi(now_kubernetes_cluster_sign_kubeconfig)
        old_k8s_api = K8sApi(old_kubernetes_cluster_sign_kubeconfig)

        try:
            now_data = now_k8s_api.get_namespaced_deployment(now_version_cluster_select_name)
            old_data = old_k8s_api.get_namespaced_deployment(old_version_cluster_select_name)

            return_data = []
            for old_data_one in old_data:
                if_ = 1
                for now_data_one in now_data:
                    if now_data_one['name'] == old_data_one['name']:
                        return_data.append({
                            "id": now_data_one['name'],
                            "now_version_pod_name": now_data_one['name'],
                            "now_version_pod_image": now_data_one['containers_str'],
                            "old_version_pod_name": old_data_one['name'],
                            "old_version_pod_image": old_data_one['containers_str'],
                        })
                        if_ = 0
                if if_:
                    return_data.append({
                        "id": old_data_one['name'],
                        "now_version_pod_name": "",
                        "now_version_pod_image": "",
                        "old_version_pod_name": old_data_one['name'],
                        "old_version_pod_image": old_data_one['containers_str'],
                    })

        except Exception as e:
            return Result.fail_response(msg=str(e))
        return Result.success_response(data=return_data, msg='查询成功')
